package com.baidu.logindemos.ui.main

import android.content.Intent
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import androidx.core.widget.addTextChangedListener
import com.baidu.logindemos.databinding.ActivityMainBinding
import com.baidu.logindemos.ui.base.BaseActivity
import com.baidu.logindemos.ui.welcome.WelcomeActivity
import com.baidu.logindemos.utils.DialogUtil

class MVPMainActivity : BaseActivity<ActivityMainBinding>(), ILoginView {
    private val mPresenter: ILoginPresenter = ILoginPresenterImpl.getInstance(this)

    override fun initViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initUI() {
        showWelecome()

        //监听按钮的点击事件
        mBinding.loginBtn.setOnClickListener {
            mPresenter.login()
        }
        //输入框的内容改变的事件
        mBinding.etName.addTextChangedListener(afterTextChanged = {
            mPresenter.nameChanged(it.toString())
        })
        mBinding.etPassword.addTextChangedListener(afterTextChanged = {
            mPresenter.passwordChanged(it.toString())
        })

        mBinding.ivEye.setOnClickListener { mPresenter.eyeClicked() }
    }

    private fun showWelecome(){
        startActivity(Intent(this, WelcomeActivity::class.java))
    }

    override fun showOK() {
        DialogUtil.instance.showOK(this){}
    }

    override fun showError(error: String) {
        DialogUtil.instance.showError(this, error){
            mBinding.etName.text.clear()
            mBinding.etPassword.text.clear()
        }
    }

    override fun changeBtnEnableStatus(enabled: Boolean) {
        mBinding.loginBtn.isEnabled = enabled
    }

    override fun changeEyeResource(id: Int, isPassword: Boolean) {
        mBinding.ivEye.setImageResource(id)
        if (isPassword){
            mBinding.etPassword.transformationMethod = PasswordTransformationMethod()
        }else{
            mBinding.etPassword.transformationMethod = HideReturnsTransformationMethod()
        }
        mBinding.etPassword.setSelection(mBinding.etPassword.text.length)
    }
}